/*
* 新增收料单
* */

import 'dart:convert';

import 'package:center_beijing/api/material_science_api.dart';
import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_input_widget.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_select_widget.dart';
import 'package:center_beijing/widgets/imageSelect_widget.dart';
import 'package:center_beijing/widgets/selectRow_widget.dart';
import 'package:center_beijing/widgets/select_widget.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart' as Go;
import 'package:dio/dio.dart' as ImageForm;
import 'package:images_picker/images_picker.dart';
import 'dart:io';
import 'package:http_parser/http_parser.dart';
class AddMaterialWarehousing extends StatefulWidget {
  @override
  _AddMaterialWarehousingState createState() => _AddMaterialWarehousingState();
}

class _AddMaterialWarehousingState extends State<AddMaterialWarehousing>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  var currentDetail = Go.Get.arguments;
  final TextEditingController receiver = TextEditingController();
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  List<SelectItems> supplierList = [];//供应商
  SelectItems supplier = SelectItems();
  List<SelectItems> receiptType = [
    SelectItems(label: '收料', value: '1'),
    SelectItems(label: '退料', value: '2')
  ];
  SelectItems receipt = SelectItems();
  List<SelectItems> factoriesList = [];
  SelectItems selectFactory = SelectItems();
  List<Media> photos = [];
  ImageForm.FormData formData;
  List passPhoto = [];

  var receivingTime = '';

  @override
  void initState() {
    _controller = AnimationController(vsync: this);
    super.initState();

    this.getAllSupplier();
    this.getWarehouse();
    if(currentDetail!=null){
      this.setState(() {
        receivingTime =currentDetail['receiptDateStr']!=null?(currentDetail['receiptDateStr'].replaceAll('/', '-')):'';
        receiver.text = currentDetail['receiver']!=null?currentDetail['receiver']:'';
        receipt = currentDetail['receiptType']=='1'?SelectItems(label: '收料', value: '1'):SelectItems(label: '退料', value: '2');
      });
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  /*
  * 获取供应商
  * */
  getAllSupplier() async {
    var result =
        await getSupplier({'sectionId': GlobalConfig.selectFactory.tag});
    if (result != null) {
      List<SelectItems> tem = [];
      result.forEach((item) {
        tem.add(SelectItems(
            label: item['supplierName'], value: item['corpId'], dict: item));
      });
      this.setState(() {
        supplierList = tem;
        if(currentDetail!=null){
          supplierList.forEach((element) {
            if(element.value==currentDetail['supplierCorporationId']){
              supplier = element;
            }
          });
        }
      });
    }
    LogUtil.d(result);
  }

  /*
  * 获取仓库
  * */
  getWarehouse() async {
    var result =
    await getInWarehouse({'projectSectionId': GlobalConfig.selectFactory.tag,'houseType':'1'});
    if (result != null) {
      List<SelectItems> tem = [];
      result.forEach((item) {
        tem.add(SelectItems(
            label: item['houseName'], value: item['id'].toString(), dict: item));
      });
      this.setState(() {
        factoriesList = tem;
        if(currentDetail!=null){
          factoriesList.forEach((element) {
            if(element.value==currentDetail['outHouseId'].toString()){
              selectFactory = element;
            }
          });
        }
      });
    }
    LogUtil.d(result);
  }

  justifyInfo() {
    if(supplier.value==null){
      Fluttertoast.showToast(msg: '请选择供应商');
      return false;
    }else if(receivingTime==''){
      Fluttertoast.showToast(msg: '请选择收料时间');
      return false;
    }else if(receipt.value==null){
      Fluttertoast.showToast(msg: '请选择收料类型');
      return false;
    }else if(selectFactory.value==null){
      Fluttertoast.showToast(msg: '请选择仓库');
      return false;
    }
    return true;
  }

  submit() async {
    var pass = {
      'item': json.encode({
        'id':'',
        'projectSectionId': GlobalConfig.selectFactory.tag,
        'receiptType': receipt.value,
        'supplierCorporationId': supplier.value,
        'outHouseId': selectFactory.value,
        'receiptDate': receivingTime,
        'receiver': receiver.text,
        'attachmentList': passPhoto,
      })
    };
    var result = await addReceivedSheet(pass);
    loading.dismiss();
    if (result != null&&result['hasError']==null) {
      Fluttertoast.showToast(msg: '提交成功');
      bus.emit('refreshReceiveList');
      Go.Get.back();
    }
  }

  Future addImage() async {
    this.passPhoto = [];

    loading.show(delay: 30);
    if (this.photos.length > 0) {
      var temPhotos = [];
      temPhotos.addAll(this.photos);
      formData = new ImageForm.FormData.fromMap({
        "tenantId": GlobalConfig.tenantId,
      });
      for (int i = 0; i < temPhotos.length; i++) {
        Media asset = temPhotos[i];
        File file = File(asset.path);
        formData.files.add(MapEntry("files",
            await ImageForm.MultipartFile.fromFile(file.path.toString(),contentType: MediaType('image',file.path.toString().split('.').last))));
      }
      var result = await uploadImage(formData, GlobalConfig.tenantId);
      if (result != null && result.length > 0) {
        result.forEach((element){
          element['atchId'] = element['attachmentId'];
          element['fileType'] = 'png';
          element['fileName'] = element['fileName'].toString().substring(element['fileName'].length-8);
        });
        this.passPhoto = result;
        this.submit();
      }
    } else {
      this.submit();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('新增收料单'),
        ),
        body: Container(
          color: Styles.MainBackgroundColor,
          padding: EdgeInsets.fromLTRB(
              0, 0, 0, MediaQuery.of(context).padding.bottom + 70),
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                  child: CustomSelectWidget(
                    require: true,
                    rightText: supplier.label != null ? supplier.label : '请选择',
                    items: supplierList,
                    selectCallback: (value) => this.setState(() {
                      supplier = value;
                    }),
                    title: '供应商',
                  ),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                  color: Colors.white,
                  padding: EdgeInsets.fromLTRB(Styles.spacing8, 0, 0, 0),
                  child: SelectRow(
                      titleFont: Styles.MiddleFont17,
                      require: true,
                      title: '收料时间',
                      rightText: receivingTime,
                      selectCallback: (value) {
                        this.setState(() {
                          receivingTime = value;
                        });
                      }),
                ),
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                  child: CustomSelectWidget(
                    require: true,
                    rightText: receipt.label != null ? receipt.label : '请选择',
                    items: receiptType,
                    selectCallback: (value) => this.setState(() {
                      receipt = value;
                    }),
                    title: '收料类型',
                  ),
                ),
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                  child: CustomSelectWidget(
                    require: true,
                    rightText: selectFactory.label != null
                        ? selectFactory.label
                        : '请选择',
                    items: factoriesList,
                    selectCallback: (value) => this.setState(() {
                      selectFactory = value;
                    }),
                    title: '仓库',
                  ),
                ),
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                  padding: EdgeInsets.fromLTRB(
                      Styles.spacing8, 0, Styles.spacing8, 0),
                  child: CustomInput(
                    inputformat: [
                      LengthLimitingTextInputFormatter(10),
                    ],
                    title: '领料人',
                    placeHold: '请输入',
                    textInput: this.receiver,
                    clearAll: false,
                    require: false,
                  ),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                  color: Colors.white,
                  child: Column(
                    children: [
                      Padding(
                        padding: EdgeInsets.fromLTRB(
                            Styles.spacing16, Styles.spacing8, 0, 0),
                        child: Row(
                          children: <Widget>[
                            Text(
                              '照片(${this.photos.length}/6)',
                              style: TextStyle(
                                  color: Styles.DetailColor,
                                  fontSize: Styles.MiddleFont17),
                            ),
                          ],
                        ),
                      ),
                      ImageSelectWidget(
                        onchange: (value) {
                          this.setState(() {
                            photos = value;
                          });
                        },
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                FocusScope.of(context).requestFocus(new FocusNode());
                if (this.justifyInfo()) {
                  showDialog(
                      barrierDismissible: false,
                      context: this.context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: Text('注意'),
                          content: Text('确认提交吗？'),
                          actions: <Widget>[
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "取消",
                                  style: TextStyle(color: Colors.black),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            ),
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "确定",
                                  style: TextStyle(color: Colors.red),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                  this.addImage();
                                },
                              ),
                            ),
                          ],
                        );
                      });
                }
              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '确认提交',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
